# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/5/25 15:43
# @Author  : qiaoc
# @File    : SchedulerTask.py
# @Desc    :
from dao.PyMysql import *
from examine import AuditEle
from examine import AuditWriteOff
import os
import shutil
import socket
import os
import platform
import ctypes


switch = True


def getAuditOrder():
    """
        获取稽核工单，进行稽核
    :return:
    """
    global switch
    print("=========执行定时稽核任务=============")
    sql = """ SELECT * FROM rpa_timing_audit where status = 0 and ip = '"""+ get_host_ip()+ """' """
    audit_list = PyMysql().get_db_data(sql)
    if not len(audit_list):
        return ;
    if switch:
        print("=========开始进行稽核任务=============")
        for i,info in enumerate(audit_list):
            switch = False
            type = info['type'] # 缴费单类型
            code = info['code'] # 缴费单编码
            affix_path = info['affix_path'] #附件路径
            print('===========工单【'+code+'】开始稽核=============')
            if type == '1' or type == 1:
                # 电费
                print(AuditEle.audit_ele(code, affix_path, '1'))
            elif type == '2' or type == 2:
                # 核销
                print(AuditWriteOff.audit_write_off(code, affix_path, '2'))
            # elif type == '3':
            #     # 固化
            #     address_name = sys.argv[4]
            #     pricess = sys.argv[5]
            #     print(AuditCuring.audit_curing(bill_number, floder_path, address_name, pricess, '3'))
            # 稽核完成后，更新爬取工单状态，删除附件
            usql = """ update rpa_timing_audit set status = 1 where code = '""" + code + """'"""
            PyMysql().execute_sql(usql)
            # shutil.rmtree(affix_path)
            if i == len(audit_list) - 1 :
                switch = True
                print('==========工单稽核任务完成=========')


def cleanDisk():
    """
        清理磁盘空间
    :return:
    """
    print('==========检查磁盘空间=========')
    disk = get_free_space_mb(r"E:\\")
    if disk <= 30 :
        switch = False
        del_files(r"E:\\uibot\\内蒙附件\\报账点电费审核")
        del_files(r"E:\\uibot\\内蒙附件\\报账点核销审核")
        del_files(r"E:\\uibot\\内蒙附件\\电费固化信息审核")
        switch = True


def get_free_space_mb(folder):
    """
    获取磁盘剩余空间
    :param folder: 磁盘路径 例如 D:\\
    :return: 剩余空间 单位 G
    """
    if platform.system() == 'Windows':
        free_bytes = ctypes.c_ulonglong(0)
        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(folder), None, None, ctypes.pointer(free_bytes))
        return free_bytes.value / 1024 / 1024 // 1024
    else:
        st = os.statvfs(folder)
        return st.f_bavail * st.f_frsize / 1024 // 1024


def del_files(filepath):
    """删除指定文件夹下所有文件和文件夹"""
    del_list = os.listdir(filepath)
    for f in del_list:
        file_path = os.path.join(filepath, f)
        if os.path.isfile(file_path):
            os.remove(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)


def get_host_ip():
    """
    查询本机ip地址
    :return:
    """
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.connect(('8.8.8.8',80))
        ip=s.getsockname()[0]
    finally:
        s.close()
    return ip
